//
//  AppDelegate.m
//  Comic
//
//  Created by 程锦 on 16/3/9.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "AppDelegate.h"
#import "ComicViewController.h"
#import "HotViewController.h"
#import "VideoViewController.h"
#import "HAChatViewController.h"
#import "EaseConversationListViewController.h"
#import <EaseMobSDKFull/EaseMob.h>
#import "EaseUI.h"
#import <SMS_SDK/SMSSDK.h>
#import <SMS_SDK/Extend/SMSSDK+AddressBookMethods.h>
#import "ConversationListController.h"

#import "AMapViewController.h"

#define SMS_APPKEY @"10d9aa9bc4f92"
#define SMS_APPSEC @"d6d9fe5d392c5a7a2966fd3b0872610e"

@interface AppDelegate ()<UITabBarControllerDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self.window makeKeyAndVisible];
    
    
    // 漫画
    ComicViewController *comicVC = [[ComicViewController alloc] initWithNibName:NSStringFromClass([ComicViewController class]) bundle:nil];
    comicVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"漫画" image:[UIImage imageNamed:@"comic_Gray"] selectedImage:[UIImage imageNamed:@"comic_Yellow"]];
    UINavigationController *comicNA = [[UINavigationController alloc] initWithRootViewController:comicVC];
    
    
    // 发现热门
    HotViewController *hotVC = [[HotViewController alloc] initWithNibName:NSStringFromClass([HotViewController class]) bundle:nil];
    hotVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"发现" image:[UIImage imageNamed:@"hot_Gray"] selectedImage:[UIImage imageNamed:@"hot_Yellow"]];
    UINavigationController *hotNA = [[UINavigationController alloc] initWithRootViewController:hotVC];
    
    
    // 视频
    VideoViewController *videoVC = [[VideoViewController alloc] initWithNibName:NSStringFromClass([VideoViewController class]) bundle:nil];
    videoVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"视频" image:[UIImage imageNamed:@"video_Gray"] selectedImage:[UIImage imageNamed:@"video_Yellow"]];
    UINavigationController *videoNA = [[UINavigationController alloc] initWithRootViewController:videoVC];
    
    
    // 通讯
    ConversationListController *chatVC = [[ConversationListController alloc] initWithStyle:UITableViewStylePlain];
//    TestViewController *chatVC = [[TestViewController alloc]init];
    chatVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"聊天" image:[UIImage imageNamed:@"chat_Gray"] selectedImage:[UIImage imageNamed:@"chat_Yellow"]];
    UINavigationController *chatNA = [[UINavigationController alloc] initWithRootViewController:chatVC];
    
    
    //地图
    AMapViewController *mapVC = [[AMapViewController alloc] init];
    
    mapVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"地图" image:[UIImage imageNamed:@"comic_Gray"] selectedImage:[UIImage imageNamed:@"comic_Yellow"]];
    
    UINavigationController *mapNA = [[UINavigationController alloc]initWithRootViewController:mapVC];
    
    // 创建tabbarController
    UITabBarController *tabBarVC = [[UITabBarController alloc] init];
    tabBarVC.tabBar.tintColor = [UIColor colorWithRed:1 green:0.838 blue:0 alpha:1.000];
    // 设置管理NAVC
    tabBarVC.viewControllers = @[comicNA,hotNA,videoNA,chatNA,mapNA];
    
    // 设置window的根视图控制器
    self.window.rootViewController = tabBarVC;
    
    // 签协议
    tabBarVC.delegate = self;
    
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"dlshean#comic1135" apnsCertName:nil];
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    [[EaseSDKHelper shareHelper] easemobApplication:application didFinishLaunchingWithOptions:launchOptions appkey:@"dlshean#comic1135" apnsCertName:nil otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    // 短信验证
    [SMSSDK registerApp:SMS_APPKEY withSecret:SMS_APPSEC];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[EaseMob sharedInstance] applicationWillTerminate:application];
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "cj.Comic" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Comic" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Comic.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
